﻿/*
 * This software is the confidential and proprietary
 * information of NetBay
 * Such confidential information should not be disclosed
 * NetBay copyright(c) 2010
 */

#region Using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
#endregion

namespace NetBay.Core.Extensions
{
    /// <summary>
    /// Class handle extension for class Enum
    /// </summary>
    public static class EnumEx
    {
        /// <summary>
        /// Extension(Enum) : Retreive the "DescriptionAttribute()" from an enum's item
        /// </summary>
        /// <param name="eInstance">instance of enum's item</param>
        /// <returns>the "DescriptionAttribute()"</returns>
        public static string szGetDescription(this Enum eInstance)
        {
            string sDescription;
            DescriptionAttribute da;

            FieldInfo fi = eInstance.GetType().GetField(eInstance.ToString());
            da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
            sDescription = da != null ? da.Description : eInstance.ToString();

            return sDescription;
        }

        /// <summary>
        /// Retreive the value of a Enum from its description attribute
        /// </summary>
        /// <param name="p_tType">enum's type</param>
        /// <param name="Description">Description attribute</param>
        /// <returns>the enum that match with description</returns>
        public static Enum eGetEnumValueFromDescription(Type p_tType, string Description)
        {
            return Enum.GetValues(p_tType).Cast<Enum>().FirstOrDefault(e => e.szGetDescription().ToLower() == Description.ToLower());
        }

        private static IEnumerable<T> GetEnumeration<T>(T values)
        {
            if (!typeof(T).IsSubclassOf(typeof(Enum)))
                throw new Exception("Must be an Enum");

            int[] allValues = (int[])Enum.GetValues(typeof(T));

            int intValues = Convert.ToInt32(values);
            return from i in allValues where (i & intValues) != 0 select (T)Enum.ToObject(typeof(T), i);
        }

    }

}
